package cn.com.fattiger.framework.remoting.netty4.server.channel;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.timeout.IdleStateHandler;
import cn.com.fattiger.framework.remoting.netty4.common.protocol.handle.ReceivedHandle;
import cn.com.fattiger.framework.remoting.netty4.server.coder.Decoder;
import cn.com.fattiger.framework.remoting.netty4.server.coder.Encoder;
import cn.com.fattiger.framework.remoting.netty4.server.handle.ServerHandlerAdapter;
import cn.com.fattiger.framework.remoting.server.Server;

public class ServerChannelInitializer extends ChannelInitializer<SocketChannel> {
	private final ReceivedHandle receivedHandle;
	private final Server server;
	private final String hostName;

	public ServerChannelInitializer(Server server, ReceivedHandle receivedHandle, String hostName) {
		super();
		this.server = server;
		this.receivedHandle = receivedHandle;
		this.hostName = hostName;
	}

	@Override
	protected void initChannel(SocketChannel ch) throws Exception {
		ChannelPipeline pipeline = ch.pipeline();
		//pipeline.addLast(new ServerRequestEncoder(protocol));
		//pipeline.addLast(new ServerRequestDecoder(protocol));
		
		pipeline.addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE,0, 4, 0, 4));
		pipeline.addLast(new LengthFieldPrepender(4));
		pipeline.addLast(new Encoder());
		pipeline.addLast(new Decoder());

		pipeline.addLast(new IdleStateHandler(30, 0, 0));
		pipeline.addLast(new ServerHandlerAdapter(server, receivedHandle, hostName));
	}

}
